package cn.com.xy.sms.sdk.net.util;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
	/**
	 * 密钥算法
	 */
	private static final String KEY_ALGORITHM = "AES/CBC/PKCS5Padding";
	private static final String KEY_AES = "AES";
	private static final int KEY_SIZE = 128;

	public static byte[] iv1 = {(byte) 0x12, (byte) 0x34, (byte) 0x56,
		(byte) 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, (byte) 0xA9, (byte) 0xB7, (byte) 0xC8,
		(byte) 0xD6, (byte) 0xE3, (byte) 0xF1, (byte) 0x1F, (byte) 0xFE};


    /**
     * 获取密钥
     *
     * @return
     * @throws Exception
     */
    public static byte[] initSecretKey() throws Exception {
        //实例化
        KeyGenerator kg = KeyGenerator.getInstance(KEY_AES);
        //AES 要求密钥长度为128位、192位或256位
        kg.init(KEY_SIZE);
        //生成密钥
        return kg.generateKey().getEncoded();
    }


    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        //还原密钥
        Key k = new SecretKeySpec(key, KEY_AES);
        /**
         * 实例化
         * 使用PKCS7Padding填充方式，按如下方式实现
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC");
         */
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        //初始化，设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, k, new IvParameterSpec(iv1));
        //执行操作
        return cipher.doFinal(data);
    }

    /**
     * 解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        //还原密钥
        Key k = new SecretKeySpec(key, KEY_AES);
        /**
         * 实例化
         * 使用PKCS7Padding填充方式，按如下方式实现
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC");
         */
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        //初始化，设置解密模式
        cipher.init(Cipher.DECRYPT_MODE, k, new IvParameterSpec(iv1));
        //执行操作
        return cipher.doFinal(data);
    }

}
